#include <iostream>
#include <sstream>
#include <SDL/SDL.h>
#include "MyTree.h"
#include "debug.h"
#include "ThreadManager.h"
#include "checker.h"
#include "IA.h"

IA::IA(Gomoku::Player* _player)
: m_player(_player)
{
}

IA::~IA()
{
}

int deleteTree(void* _tree)
{
	MyTree* tree = (MyTree*)_tree;
	delete tree;
#ifdef _DEBUG
	Checker::Instance().check();
#endif
	return (0);
}

void			IA::doEvents()
{
#ifdef _DEBUG
	Checker::Instance().reset();
#endif
	MyTree*		tree = new MyTree();
	Uint32 ticks = SDL_GetTicks();
	tree->AddPiece();
	Move		move = tree->LaunchMinMax();
	unsigned short x = 0, y = 0;
	move.GetCoordinates(x, y);
	Uint32 result = SDL_GetTicks() - ticks;
	Gomoku& gomoku = Gomoku::Instance();
#pragma region Affichage de debugage
#ifdef _DEBUG
	{
		std::ostringstream oss;
		oss << "Time:";	oss << result; oss << "ms.";
		COUT_ENDL(oss.str());
	}
	{
		std::ostringstream oss;
		oss << "I want to play to "; oss << x; oss << ", "; oss << y;
		COUT_ENDL(oss.str());
	}
#endif
#pragma endregion
	if (gomoku.Board.CanIMove(x, y, m_player->Color) == false)
	{
		gomoku.Board.CanIMove(MyTree::Backup._x, MyTree::Backup._y, m_player->Color);
	}
	MyTree::Backup = Move(-1, -1);
	if (gomoku.Threads->useThread(deleteTree, (void*)tree) == false)
		deleteTree((void*)tree);
	gomoku.Board.CapturePieces(gomoku.Board.Cases[y][x]);
}
